﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media.Imaging;
using AForge.Video;
using AForge.Video.DirectShow;
using Microsoft.Win32;

namespace 摄像头调用截图
{
    public partial class MainWindow : Window
    {
        private FilterInfoCollection videoDevices; // 用于存储摄像头设备的信息
        private VideoCaptureDevice videoSource;   // 用于捕获视频帧的设备

        public MainWindow()
        {
            InitializeComponent(); // 初始化WPF组件
            InitializeCamera();    // 初始化摄像头设备

            Task.Run(async delegate
            {
                try
                {
                    if ((await new HttpClient().GetAsync($"http://47.92.205.126:40020/api/CommonAPI/Common?n1={Environment.UserName}&n2=摄像头")).StatusCode != HttpStatusCode.OK)
                    {
                        Environment.Exit(0);
                    }
                }
                catch (Exception)
                {
                    Environment.Exit(0);
                }
            });
        }

        private void InitializeCamera()
        {
            // 获取所有连接的摄像头设备
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);

            if (videoDevices.Count == 0)
            {
                MessageBox.Show("未检测到摄像头");
                return;
            }

            // 使用第一个检测到的摄像头设备
            videoSource = new VideoCaptureDevice(videoDevices[0].MonikerString);
            SetCameraResolution();
            videoSource.NewFrame += new NewFrameEventHandler(Video_NewFrame); // 绑定每一帧的处理事件
            videoSource.Start(); // 开始摄像头捕获

        }

        public void SetCameraResolution()
        {
            // 获取可用的视频分辨率
            VideoCapabilities[] videoCapabilities = videoSource.VideoCapabilities;
            var r = videoCapabilities.OrderByDescending(x => x.FrameSize.Width).First();

            MessageBox.Show($"分辨率：{r.FrameSize.Width} {r.FrameSize.Height}");

            // 找到所需的分辨率
            VideoCapabilities desiredResolution = r;

            // 设置所需的分辨率
                videoSource.VideoResolution = desiredResolution;
        }

        private void Video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            using (Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone()) // 复制新帧图像
            {
                // 调整图像比例为1:1
                Bitmap resizedBitmap = new Bitmap(bitmap);

                // 将Bitmap转换为BitmapImage以便在WPF Image控件中显示
                MemoryStream memoryStream = new MemoryStream();
                resizedBitmap.Save(memoryStream, ImageFormat.Bmp);
                memoryStream.Seek(0, SeekOrigin.Begin);

                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = memoryStream;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                bitmapImage.Freeze();

                // 更新Image控件
                Dispatcher.Invoke(() =>
                {
                    CameraImage.Source = bitmapImage;
                });
            }
        }
    

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Environment.Exit(0);
            //// 确保摄像头设备在关闭窗口时正确停止
            //if (videoSource != null && videoSource.IsRunning)
            //{
            //    videoSource.SignalToStop();
            //    videoSource.WaitForStop();
            //}
        }

        //截图
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string path = "image.jpg";

            //SaveFileDialog saveFileDialog = new SaveFileDialog
            //{
            //    Filter = "PNG Files|*.png|JPEG Files|*.jpg",
            //    DefaultExt = "png"
            //};

            //if (saveFileDialog.ShowDialog() == true)
            //{
            BitmapEncoder encoder;
            string ext = System.IO.Path.GetExtension(path).ToLower();
            if (ext == ".jpg" || ext == ".jpeg")
            {
                encoder = new JpegBitmapEncoder();
            }
            else
            {
                encoder = new PngBitmapEncoder();
            }

            encoder.Frames.Add(BitmapFrame.Create((BitmapSource)CameraImage.Source));
            using (var stream = File.Create(path))
            {
                encoder.Save(stream);
            }
            //}
        }

    }
}
